package com.hb.controller.sys;

import cn.hutool.crypto.asymmetric.RSA;
import com.hb.config.prop.PasswordProperties;
import com.hb.model.Result;
import com.hb.service.role.RoleService;
import com.hb.utils.RsaUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;
import javax.annotation.Resource;
import javax.validation.constraints.NotNull;


@RestController
@RequestMapping("sys")
@Api(tags = "System Related interfaces")
@Log4j2
public class LoginController {

	@Resource
	private RoleService roleService;

	@Resource
	private PasswordProperties passwordProperties;

	/**
	 * Role login
	 */
	@ApiOperation(value = "login", notes = "Backend login")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "username", value = "username", paramType = "query", required = true, dataType = "String", dataTypeClass = String.class),
			@ApiImplicitParam(name = "password", value = "password", paramType = "query", required = true, dataType = "String", dataTypeClass = String.class),
	})
	@PostMapping("login")
	public Result login(@ApiIgnore @NotNull(message = "username cannot be empty") String username,
						@ApiIgnore @NotNull(message = "password  cannot be empty") String password) {
		RSA rsa = new RSA(passwordProperties.getPrivateKey(), passwordProperties.getPublicKey());
		String hMacDgestHex = RsaUtil.getHMacDgestHex(rsa, username, password);
		UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, hMacDgestHex);
		SecurityUtils.getSubject().login(usernamePasswordToken);
		return Result.success(roleService.selectByRoleName(username));
	}

	/**
	 * Role logout
	 */
	@ApiOperation(value = "logout", notes = "Backend logout")
	@PostMapping("logout")
	public Result logout() {
		SecurityUtils.getSubject().logout();
		return Result.success();
	}


}
